import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import HeaderView from '@/views/HeaderView.vue'
import FooterView from '@/views/FooterView.vue'
import store from '../store/index.js'

import {findArrayIsSame} from '@/utils/utils'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
//路由表
const routes = [
  {
    path: '/',
    name: 'home',
    //页面结构：上中下
    components:{
      default:HomeView,
      header:HeaderView,
      footer:FooterView

    }

  },
  {
    path: '/about', //路由路径
    name: 'about',// 命名路由
    //懒加载   webpackChunkName 进行分包
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
 
  {

    path: '/my',
    name: 'my',
   
    component: () => import(/* webpackChunkName: "about" */ '../views/my/MyView.vue')
  },
  {
    path: '/my/info',
    name: 'my-info',//my-*
    component: () => import(/* webpackChunkName: "about" */ '../views/my/InfoView.vue')
  },
  {
    path: '/my/article',
    name: 'my-article',//my-*
    component: () => import(/* webpackChunkName: "about" */ '../views/my/ArticleView.vue')
  },
  {

    path: '/login',
    name: 'login',
   
    component: () => import(/* webpackChunkName: "about" */ '../views/LoginView.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import(/* webpackChunkName: "about" */ '../views/RegisterView.vue')
  },
  {

    path:'/forgetpassword',
    name:'forgetpassword',
    component:()=>import('../views/ForgetPasswordView.vue')
  },
  {

    path:'/articledetail',
    name:'articledetail',
    component:()=>import('../views/ArticledetailView.vue')
  }


]
//路由
const router = new VueRouter({
  mode: 'history', //hash
  base: process.env.BASE_URL,
  routes //路由表加载
})
//路由守卫
// 拦截路由
router.beforeEach((to,from,next)=>{
  store.commit('setPreRoute',from.path)

  let excludeArray=["/","/register","/login"];// 不要拦截的路由

  let token=store.state.$token
  console.log("token",token)
  //console.log(findArrayIsSame(to.path,excludeArray));
  if(findArrayIsSame(to.path,excludeArray)){
      //排除不需要授权的页面
      next();
  }
  else if(token==''){
    
    //未登录，进入登陆页面
    next({name:'login'});
    
  }
  else{
    //判断是否有权限
    next()
  }

})

export default router
